//
//  RssFeed.m
//  RssRead
//
//  Created by 旺财 on 10-11-1.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "RssFeed.h"
#import "Common.h"

@implementation RssFeed


@synthesize stories;
@synthesize notreadcount;
@synthesize lastUpdateState;



- (void)parseXMLFileAtURL:(NSString *)URL cachefile:(NSString *)md5path isforce:(BOOL)force updateRss:(NSInteger) timer
{	
	lastUpdateState=0;
 	stories = [[NSMutableArray alloc] init];
	// retaincount=1
	
	filepath=md5path;
    NSURL *xmlURL = [NSURL URLWithString:URL];
	notreadcount=0;
	if (timer==0) {
		force=YES;
	}
	
	if (![[NSFileManager defaultManager] fileExistsAtPath:md5path] || force) 
	{
		myData = [NSData dataWithContentsOfURL:xmlURL];
	}
	else
	{
		NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:md5path error:nil];
		NSDate *mtime=[fileAttributes fileCreationDate];
		NSTimeInterval ti=[mtime timeIntervalSinceNow];
		if ((ti*-1)<(timer*60))
		{
			stories= [NSMutableArray arrayWithContentsOfFile:filepath];
			//retain count =1
			for(NSMutableDictionary* dic in stories) 
			{
				if ([dic objectForKey:@"isread"]!=nil)
				{
					NSString *tem=[dic objectForKey:@"isread"];
					if ([tem isEqualToString:@"no"])
					notreadcount++;
				}
			}
			return ;
		}
		else
		{
			myData = [NSData dataWithContentsOfURL:xmlURL];	
		}
		

	}
		rssParser = [[NSXMLParser alloc] initWithData:myData];
		[rssParser setDelegate:self];
		[rssParser setShouldProcessNamespaces:NO];
		[rssParser setShouldReportNamespacePrefixes:NO];
		[rssParser setShouldResolveExternalEntities:NO];
		[rssParser parse];
}


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
	
	//gb2312处理	
	if ([parseError code]==31)
	{
		NSString *myStr = [[NSString alloc] initWithData:myData encoding:0x80000632];
		[myStr stringByReplacingOccurrencesOfString:@"encoding=\"gb2312\"" withString:@""];
		myData = [myStr dataUsingEncoding:NSUTF8StringEncoding];
		[myStr release];
		rssParser = [[NSXMLParser alloc] initWithData:myData];
		[rssParser setDelegate:self];
		// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
		[rssParser setShouldProcessNamespaces:NO];
		[rssParser setShouldReportNamespacePrefixes:NO];
		[rssParser setShouldResolveExternalEntities:NO];
		[rssParser parse];
	}
	else 
	{
		lastUpdateState=-1;
		if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) 
		{
			stories= [NSMutableArray arrayWithContentsOfFile:filepath];
			
		}
		else
		{
			stories=nil;
		}
		
		
		//更新失败
		//notreadcount=-1;
		//NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
		//NSLog(@"error parsing XML: %@", errorString);
		//UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		//[errorAlert show];
	}

}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{			
    currentElement = [elementName copy];
	if ([elementName isEqualToString:@"item"]) 
	{
		// clear out our story item caches...
		item = [[NSMutableDictionary alloc] init];
		currentTitle = [[NSMutableString alloc] init];
		currentDate = [[NSMutableString alloc] init];
		currentSummary = [[NSMutableString alloc] init];
		currentLink = [[NSMutableString alloc] init];
		currentShortSummary=[[NSMutableString alloc] init];
		
	}
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
	if ([elementName isEqualToString:@"item"]) 
	{
		// save values to an item, then store that item into the array...
		[item setObject:currentTitle forKey:@"title"];
		[item setObject:currentLink forKey:@"link"];
		[item setObject:currentSummary forKey:@"summary"];
		[item setObject:currentDate forKey:@"date"];
		[item setObject:@"detail" forKey:@"vtype"];
		[item setObject:@"no" forKey:@"isread"];

		currentShortSummary=[NSString stringWithString: [Common flattenHTML:(NSString *)currentSummary]];
		
		if (currentShortSummary!=nil && [currentShortSummary length]>40)
			currentShortSummary=[currentShortSummary substringToIndex:40]; 
		[item setObject:currentShortSummary forKey:@"short"];
		[stories addObject:item];
		[item release];
		//NSLog(@"adding story: %@", currentTitle);
	}	
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if ([currentElement isEqualToString:@"title"]) 
	{
		[currentTitle appendString:string];
	} 
	else if ([currentElement isEqualToString:@"link"]) 
	{
		[currentLink appendString:string];
	} 
	else if ([currentElement isEqualToString:@"description"]) 
	{
		[currentSummary appendString:string];
		
	} 
	else if ([currentElement isEqualToString:@"pubDate"]) 
	{
		[currentDate appendString:string];
	}
	
	
}

- (void)parserDidEndDocument:(NSXMLParser *)parser 
{
	if(![stories writeToFile:filepath atomically:YES])
	{
		NSLog(@".plist writing was unsucessfull");
	}
	NSLog(@"abc");
	notreadcount=[stories count];
	lastUpdateState=1;
}

- (void)dealloc 
{	
	[currentElement release];
	[rssParser release];
	[stories release];
	[item release];
	[currentTitle release];
	[currentDate release];
	[currentSummary release];
	[currentLink release];	
	[currentShortSummary release];
	[super dealloc];
}

@end
